<template>
    <div class="downloadCenter">
        <div class="p-2">
            <searchrevealing>
                <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="88px">
                    <el-form-item label="文件名称" prop="originalName">
                        <el-input v-model="queryParams.originalName" placeholder="请输入" clearable style="width: 220px"
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="文件状态" prop="status">
                        <el-select v-model="queryParams.status" placeholder="请选择文件状态" clearable style="width: 220px"
                            filterable>
                            <el-option v-for="dict in ReasonstorageList" :key="dict.value" :label="dict.label"
                                :value="dict.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="生成时间" prop="outTimeArray">
                        <el-date-picker value-format="YYYY-MM-DD" v-model="queryParams.outTimeArray" type="daterange"
                            range-separator="~" start-placeholder="开始时间" end-placeholder="结束时间" clearable
                            style="width: 220px" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleQuery" :loading="queryLoading">查询</el-button>
                        <el-button @click="resetQuery" :loading="queryLoading">重置</el-button>
                    </el-form-item>
                </el-form>
            </searchrevealing>
            <el-card shadow="never">
                <template #header>

                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :name="'下载中心列表'"
                        @updateColumn="getColmun"></right-toolbar>
                </template>
                <el-table v-loading="loading" :data="selectionRecordList" border @header-dragend="dragEnd">
                    <el-table-column label="序号" type="index" width="55" align="center" :fixed="true" />
                    <el-table-column v-for="(item, index) in storageRecordColumns" :key="index" :label="item.label"
                        align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
                        <template #default="scope">
                            <span v-if="item.prop == 'status'">{{ scope.row.status == 0 ? '不可下载' : '可下载' }}</span>
                            <span v-if="item.prop == 'size'">{{ bytesToSize(Number(scope.row.size)) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
                        <template #default="scope">
                            <el-button link type="primary" v-if="scope.row.status == 2" @click="setDownload(scope.row)"
                                class="color_theme">下载</el-button>
                            <el-button link type="primary" @click="setDelete(scope.row)"
                                class="color_theme">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize" @pagination="paginationChange" />
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { getExcelList, deleteExcel } from '@/api/group/downloadCenter/index'

const { proxy } = getCurrentInstance() as any;
const storageRecordColumns = ref()
const selectionRecordList = ref<any[]>([]);
const loading = ref(true);
const total = ref(0);
const showSearch = ref(true);
const queryFormRef = ref<ElFormInstance>();


const queryLoading = ref(false)
const columnData = ref()
const ReasonstorageList = reactive([
    { label: '处理中', value: '0' },
    { label: '导出失败', value: '1' },
    { label: '导出成功', value: '2' }
])

const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 10,
    originalName: '',
    status: '',
    outTimeArray: [],
    startTime: '',
    endTime: ''
})

/** 搜索按钮操作 */
const handleQuery = () => {
    queryLoading.value = true
    queryParams.value.pageNum = 1;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};
// 文件大小单位转换
const bytesToSize = (size: number) => {
    let sizeStr: string;
    if (size < 0.1 * 1024) {
        // 小于0.1KB，则转化成B
        sizeStr = size.toFixed(2) + "B";
    } else if (size < 0.1 * 1024 * 1024) {
        // 小于0.1MB，则转化成KB
        sizeStr = (size / 1024).toFixed(2) + "KB";
    } else if (size < 0.1 * 1024 * 1024 * 1024) {
        // 小于0.1GB，则转化成MB
        sizeStr = (size / (1024 * 1024)).toFixed(2) + "MB";
    } else {
        // 其他转化成GB
        sizeStr = (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
    }

    // 获取小数点处的索引
    const index = sizeStr.indexOf(".");
    // 获取小数点后两位的值
    const dou = sizeStr.substr(index + 1, 2);

    // 判断后两位是否为00，如果是则删除00
    if (dou === "00") return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2);

    return sizeStr;
}
// 下载
const setDownload = async (row: any) => {
    window.open(row.url)
}
// 删除
const setDelete = (row: any) => {
    ElMessageBox.confirm(
        '是否删除此条数据？',
        '删除',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        loading.value = true
        try {
            await deleteExcel({ id: row.id })
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            loading.value = false
            await getList();
        } catch (error) {
            loading.value = false
        }
    })
}

/** 获取colmun */
const getColmun = async () => {
    const columnDatas = await proxy?.useColumn('下载中心列表')
    storageRecordColumns.value = columnDatas.columnCustom
    columnData.value = columnDatas
    queryParams.value.pageSize = columnDatas.columnPageSize || 10
}

/** 页数变化 */
const paginationChange = async () => {
    await getList();
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
    getColmun()
}
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
    columnData.value.columnCustom.map((item: any) => {
        if (item.prop == column.property) {
            item.width = newWidth
        }
    })
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
}

/** 查询列表 */
const getList = async () => {
    try {
        loading.value = true;
        if (queryParams.value.outTimeArray && queryParams.value.outTimeArray.length) {
            queryParams.value.startTime = queryParams.value.outTimeArray[0]
            queryParams.value.endTime = queryParams.value.outTimeArray[1]
        } else {
            queryParams.value.startTime = ''
            queryParams.value.endTime = ''
        }
        const res = await getExcelList(queryParams.value);
        selectionRecordList.value = res.rows;
        total.value = res.total;
        loading.value = false;
        queryLoading.value = false
    } catch (e) {
    } finally {
        loading.value = false;
    }
};

onMounted(async () => {
    await getColmun()
    getList()
})
</script>

<style lang="scss" scoped></style>